package com.imooc.ecommerce.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;


/**
 * <p>事件推送 Aware: 动态更新路由网关 Service
 *
 * @author Yaxi.Zhang
 * @since 2022/11/3 19:42
 */
@Slf4j
@Service
@SuppressWarnings("NullableProblems")
public class DynamicRouteServiceImpl implements ApplicationEventPublisherAware {
    /**
     * <p>写路由定义
     */
    @Resource
    private RouteDefinitionWriter routeDefinitionWriter;

    /**
     * <p>获取路由定义
     */
    private RouteDefinitionLocator routeDefinitionLocator;

    /**
     * <p>事件发布
     */
    private ApplicationEventPublisher publisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }

    /**
     * <p>增加路由定义
     */
    public void addRouteDefinition(RouteDefinition definition) {
        log.info("gateway add route: [{}]", definition);
        // 保存路由并发布
        routeDefinitionWriter.save(Mono.just(definition)).subscribe();
        this.publisher.publishEvent(new RefreshRoutesEvent(this));
    }

    /**
     * <p>更新路由
     */
    public void updateList(List<RouteDefinition> definitions) {
        log.info("gateway update route: [{}]", definitions);
        // 先拿到当前 Gateway 中存储的路由定义
        List<RouteDefinition> routeDefinitionExists = routeDefinitionLocator.getRouteDefinitions().buffer().blockFirst();
        // 清除之前的路由
        if (!CollectionUtils.isEmpty(routeDefinitionExists)) {
            routeDefinitionExists.forEach(it -> deleteById(it.getId()));
        }
        // 把更新的路由定义同步到 gateway 中
        if (!CollectionUtils.isEmpty(definitions)) {
            definitions.forEach(this::updateByRouteDefinition);
        }
    }

    /**
     * <p>根据路由 id 删除路由配置
     */
    private void deleteById(String id) {
        try {
            log.info("gateway delete route by id: [{}]", id);
            routeDefinitionWriter.delete(Mono.just(id)).subscribe();
            // 发布事件通知给 gateway 更新路由定义
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
        } catch (Exception e) {
            log.error("gateway delete route error: [{}]", e.getMessage(), e);
        }
    }

    /**
     * <p>更新路由
     * <p>更新的实现策略比较简单: 删除 + 新增 = 更新
     */
    private void updateByRouteDefinition(RouteDefinition definition) {
        try {
            log.info("gateway update route: [{}]", definition);
            this.routeDefinitionWriter.delete(Mono.just(definition.getId()));
        } catch (Exception e) {
            log.error("update fail, not find route routeId: [{}]", definition.getId(), e);
        }

        try {
            this.routeDefinitionWriter.save(Mono.just(definition)).subscribe();
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
        } catch (Exception e) {
            log.error("update route fail: ", e);
        }
    }

}